/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function (root) {
  /**
  队列的先进先出,将左右节点放入队列，每次拿出一个节点，将其左右节点入队，知道队列清空
  
  
   */
  if (!root) { return [] }
  let queue = [[root, 0]]
  let res = []
  while (queue.length) {
    const n = queue.shift()
    const [node, index] = n
    if (!res[index]) {
      res[index] = [node.val]
    } else {
      res[index].push(node.val)
    }
    if (node.left) {
      queue.push([node.left, index + 1])
    }
    if (node.right) {
      queue.push([node.right, index + 1])
    }
  }
  return res

};